<?php

require_once  __DIR__ . '/includes/authenticate.php';

include_once __DIR__ . '/db_bb_connect.php';

include __DIR__ . '/mainpage.php';

$season = "2018/2019";

/// CREATE USERS LIST ///

$sql = "SELECT users.user_key, users.firstname, users.type, users.lastname, teams.playernumber AS playernumber, teams_opponents.playernumber AS playernumber_opp
FROM users 
LEFT JOIN teams ON users.user_key = teams.playerID
LEFT JOIN teams_opponents ON users.user_key = teams_opponents.playerID
WHERE (users.type = 'Player' OR users.type = 'Team') 
AND teams.season = '$season'
OR teams_opponents.season = '$season'
ORDER BY teams.playernumber";

$result = $db->query($sql);

$players = "";

while( $row = $result->fetch_assoc()){ 

  $user_key = $row['user_key']; 
  $lastname = $row['lastname']; 
  $firstname = $row['firstname']; 
  $playernumber  = $row['playernumber'];
  $playernumber_opp = $row['playernumber_opp'];

  if ($playernumber == ''){
  	$playernumber = $playernumber_opp;
  }

  $players .= "{ value: \"$user_key\", label: \"$playernumber $firstname $lastname\" },";

  }

/// CREATE TAGS LIST ///

$tags = ''; 

$sql = "SELECT tag, ID FROM video_feedback_taglist";

$result = $db->query($sql);

while( $row = $result->fetch_assoc()){ 
      $tag = $row['tag'];
      $ID = $row['ID'];

      $tags .= "{ value: \"$ID\", label: \"$tag\" },";
}  
?>
	

<div id="container-fluid">
	<div id="row">
		<div class="col-lg-4 col-md-4 col-sm-8 col-xs-8"  style="margin:0 auto; float:none;">
			<h3>Search Video Feedback</h3>
			<form method="post" id="programmer_form" action="<?php $_SERVER['PHP_SELF'] ?>">
				<div class="form-group tags">
			        <label>Action Tags</label>
			        <input type="text" name="tags" id="tags" class="form-control" placeholder="Choose your tags..."/>
		       	</div>
		        <div class="form-group players">
			        <label>Players Involved</label>
			        <input type="text" name="players" id="players" class="form-control" placeholder="Choose your players..."/>
		       	</div>

		       	<div class="form-group">
        		<input type="submit" name="submit" id="submit" class="btn btn-lg btn-block btn-default" value="Search" />
       			</div>
		    </form> 
		    <div id="results"></div>
		</div>
	</div>
</div>

<?php

if ($_POST) {

	include_once __DIR__ . '/db_bb_connect.php';


	require_once __DIR__ . '/includes/BasketbalFunctions.php';

	$basketbalfunctions = new BasketbalFunctions();

	$tags_sel = $_POST['tags'];
	$players_sel = $_POST['players'];

	$tags_explode = explode(", ", $tags_sel);
	$players_explode = explode(", ", $players_sel);

	if ( $tags_sel == '' ){
		$tags_query = "";
	} else if ( sizeof($tags_explode) == 1 ) {
		$tags_query = "FIND_IN_SET('$tags_sel',action_tags) ";
	} else if ( sizeof($tags_explode) > 1 ) {
		$tags_query = "";
		foreach ($tags_explode as $tag_sele) {
			$tags_query .=  "AND FIND_IN_SET('$tag_sele',action_tags) ";
		}

		$words = explode( ' ', $tags_query);
		array_shift( $words);
		$tags_query = implode( ' ', $words);		
	}

	if ( $players_sel == '' ){
		$players_query = "";
	} else if ( sizeof($players_explode) == 1 ) {
		$players_query = "";		
		foreach ($players_explode as $player => $user_key_sel) {
			$players_query .=  "FIND_IN_SET('$user_key_sel',players) ";
		}		
	} else if ( sizeof($players_explode) > 1 ) {
		$players_query = "";	
		foreach ($players_explode as $player => $user_key_sel) {
			$players_query .=  "AND FIND_IN_SET('$user_key_sel',players) ";
		}

		$words = explode( ' ', $players_query);
		array_shift( $words);
		$players_query = implode( ' ', $words);		
	}

   	if ($tags_query == "" OR $players_query == "") {
   		$querycomplete = "";
   	} else {
   		$querycomplete = "AND";
   	}
   	

 	$sql = "SELECT * FROM video_feedback WHERE " . $tags_query . " $querycomplete " . $players_query ;

 	$result = $db->query($sql);

 	if ($result) {
 		$numberofresults = mysqli_num_rows($result);
 	} else {
 		$numberofresults = 0;
 	}

 	

 	?>

 	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tokenfield/0.12.0/bootstrap-tokenfield.js"></script>

<div id="container-fluid">
	    <div class="row">
     <div align="center" class="col-md-8" style="margin:0 auto; float:none;">
          <h3 align="center">Video Feedback Overview</h3>
      <div id="player"></div>
     </div>
   </div>
	<div class="row">
		<div class="col-md-10" style="margin:0 auto; float:none;">
			<div id="message">
			<?php 

			 	if ($numberofresults){
			 		echo "<i>$numberofresults results found.</i><br><br>";

		 		} else {
		 			echo "<i>no results found.</i><br><br>";
		 		} 	

			?>
			</div>
		<table class="table table-hover table-striped table-condensed">
		    <thead>
		    	</thead>
		    <tbody>
		         		    
		      	<?php   

					if ($db->query($sql)) {  
						$result = $db->query($sql);
						while ($row = $result->fetch_assoc()) {
							$text = nl2br($row['comment']);
							$time_start = $row['time_start'];
							$time_end = $row['time_end'];
							$duration = $time_end - $time_start;
							$ID = $row['ID'];	

							$tags_selected = $row['action_tags'];
							$players_selected = $row['players'];		
				?>
							<tr> 
							<td> 
								<div id="player<?= $ID?>" align='center'>

 			 				</div> 
							</td>
							<td> <strong> Tags: 
								<?php 

							        $tags_split = explode(",", $tags_selected);
									foreach ($tags_split as $tag_ID) {
										$tag_name = $basketbalfunctions->GetActionTagNameFromActionTagID($tag_ID);										
										echo "<span class=\"label label-default\">$tag_name</span> ";
										}					

								?>
								
							</strong> <br>
								<strong> Players: 
								<?php 

							        $players_split = explode(",", $players_selected);
									foreach ($players_split as $user_key_select) {
										$player_firstname = $basketbalfunctions->GetUserFirstnameFromUserkey($user_key_select);
										echo "<span class=\"label label-default\">$player_firstname</span> ";
										}					

								?></strong> <br>
								<?= $text ?>	
						</td>

						<td> 

						<form method="post" action="./video_feedback_edit_entry.php"> 
						<input type="hidden" name="ID" value="<?=$ID?>"/>
						<button class="btn btn-sm btn-success edit_video_feedback_entry"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> </button>
						
						</form>
						<br>

						<form> 
						<input type="hidden" name="ID" value="<?=$ID?>"/>
						<button class="btn btn-sm btn-danger delete_video_feedback_entry"> <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> </button>
						</form></td>

							</tr>
				<?php		}		
					} else {
			      		//echo "Error: " . $sql . "<br>" . $db->error;
			    		} 				    


		      	?>
		    
		    </tbody>
		</table>

		</div>
	</div>

</div>

<script type="text/javascript">

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      <?php 

      $result = $db->query($sql);

      while ($row = $result->fetch_assoc()) { 

      	$ID = $row['ID'];

       ?>
      var player<?= $ID?>;
      var clicked<?= $ID?> = false;	   

      <?php } ?>

      function onYouTubeIframeAPIReady() {

      	<?php 

      $result = $db->query($sql);

      while ($row = $result->fetch_assoc()) { 

      	$season = $row['season'];
      	$gamenumber = $row['gamenumber'];

      	$embed_code = $basketbalfunctions->GetGameEmbedCode($season, $gamenumber);

      	$ID = $row['ID']; 

       ?>

        player<?= $ID?> = new YT.Player('player<?= $ID?>', {
          height: '150',
          width: '250',
          videoId: '<?= $embed_code?>',
          events: {
            'onStateChange': onPlayer<?= $ID?>StateChange
          }
        });

        <?php } ?>

      }

      	<?php 

      $result = $db->query($sql);

      while ($row = $result->fetch_assoc()) { 

      	$ID = $row['ID'];
      	$time_start = $row['time_start'];
		$time_end = $row['time_end'];
		$duration = ($time_end - $time_start)*1000;

       ?>

      function onPlayer<?= $ID?>StateChange(e<?= $ID?>) { 
      	if( !clicked<?= $ID?> ){	 
			  clicked<?= $ID?> = true;
			  player<?= $ID?>.seekTo(<?= $time_start?>); 
			  loop<?= $ID?>Video();
			  e<?= $ID?>.preventDefault(); 
		  };
	  
		  }


	function loop<?= $ID?>Video(){
		  var timeout = <?= $duration?>;
		  setTimeout(seek<?= $ID?>Video, timeout);          
        }

    function seek<?= $ID?>Video(){
    	player<?= $ID?>.seekTo(<?= $time_start?>);
    	loop<?= $ID?>Video();
    }

<?php }     ?>


</script>

<?php }     ?>

<script type="text/javascript">


$(document).ready(function(){

	$('#tags').tokenfield({
		autocomplete:{
		source: [<?= $tags; ?>],
		delay:100
	},
		showAutocompleteOnFocus: true
	});

	$('#players').tokenfield({
		autocomplete:{
		source: [<?= $players; ?>],
		delay:100
	},
		showAutocompleteOnFocus: true
 	});

 	<?php

if (isset($_POST['tags'])) { 

$tags_selected_explode = explode(', ', $tags_sel);

foreach ($tags_selected_explode as $tagID) {

	$sql = "SELECT tag FROM video_feedback_taglist WHERE ID = '$tagID'";

	$result = $db->query($sql);
	$row = $result->fetch_assoc();
	$tagname = $row['tag'];

  	echo "$('#tags').tokenfield('createToken', { value: '$tagID', label: '$tagname' });";
}

}

if (isset($_POST['players'])) {

$players_selected_explode = explode(', ', $players_sel);

foreach ($players_selected_explode as $selected_user_key) {

	$sql = "SELECT users.firstname, users.lastname, teams.playernumber, users.type, users.user_key
	FROM users 
	JOIN teams
	ON users.user_key = teams.playerID
	WHERE (users.type = 'Player' OR users.type = 'Team') 
	AND teams.season = '$season'
	AND users.user_key = '$selected_user_key'";

	$result = $db->query($sql);

	$row = $result->fetch_assoc();

	  $user_key = $row['user_key']; 
	  $lastname = $row['lastname']; 
	  $firstname = $row['firstname']; 
	  $playernumber = $row['playernumber'];

	echo "$('#players').tokenfield('createToken', { value: '$user_key', label: '$playernumber $firstname $lastname' });";
}

}

?>

});



	
</script>

